/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.tordroid.core.listener;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.util.Log;
import de.tordroid.core.Engine;

/**
 *
 * @author Christian Simon
 */
public class MyTabListener<T extends Fragment> implements
        ActionBar.TabListener {

    private Fragment mFragment;
    private final Activity mActivity;
    private final Class<T> mClass;

    /**
     * Constructor used each time a new tab is created.
     *
     * @param activity The host Activity, used to instantiate the fragment
     * @param tag The identifier tag for the fragment
     * @param clz The fragment's Class, used to instantiate the fragment
     */
    public MyTabListener(Activity activity, Class<T> clz) {
        mActivity = activity;
        mClass = clz;
    }

    /*
     * The following are each of the ActionBar.TabListener callbacks
     */
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // Create new Fragment
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            Engine.CURRENT_FRAGMENT = mClass.getName();
            ft.replace(Engine.FRAG_ID, mFragment, Engine.FRAG_TAG);
            Log.d("Changing Fragment", mClass.getName());
        } else {
            // Using existing Fragment
            ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_in);
            Log.d("Changing Fragment", "attaching: " + Engine.CURRENT_FRAGMENT + " to: " + mClass.getName());
            Engine.CURRENT_FRAGMENT = mClass.getName();
            if (mFragment.isDetached()) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.replace(Engine.FRAG_ID, mFragment, Engine.FRAG_TAG);
            } else {
                ft.attach(mFragment);
            }
        }

    }

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }
}
